package com.example.lightcontrol;

import java.net.Socket;

import com.example.lightcontrol.message.SyncMessageHandler;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	private static final String[] DUMMY_CREDENTIALS = new String[] {
			"foo@example.com:hello", "bar@example.com:world" };

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mUsername;
	private String mPassword;

	// UI references.
	private EditText mUserNameTextField;
	private EditText mPasswordTextField;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	
	private Button mLocalConnectionButton;
	private Button mRemoteConnectionButton;

	private SharedPreferences mSettings;
	private Socket mSocket;

	private boolean isLocalConnectionType;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		// Set up the login form.
		mUsername = getIntent().getStringExtra(EXTRA_EMAIL);
		mUserNameTextField = (EditText) findViewById(R.id.email);
		mUserNameTextField.setText(mUsername);

		mPasswordTextField = (EditText) findViewById(R.id.password);
		mPasswordTextField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});
		
		mSettings = this.getSharedPreferences( "lightControlSavedProperties", MODE_PRIVATE );
		
		if ( mSettings.contains( CommonConfig.PROPERTY_PASSWORD ) ) {
			mPasswordTextField.setText( mSettings.getString( CommonConfig.PROPERTY_PASSWORD, "") );
		}

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
		
		mLocalConnectionButton = (Button) findViewById( R.id.localConnectionButton );
		mRemoteConnectionButton = (Button) findViewById( R.id.remoteConnectionButton );
		
		mLocalConnectionButton.setOnClickListener( new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showLocalConnectionView();
			}
		});
		
		mRemoteConnectionButton.setOnClickListener( new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showRemoteConnectionView();
			}
		});

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});
		showLocalConnectionView();
	}
	
	protected void saveProperties( ) {
		SharedPreferences.Editor editor = mSettings.edit();
		if ( isLocalConnectionType() ) {
			editor.putString( CommonConfig.PROPERTY_IP, mUserNameTextField.getText().toString() );	
		} else {
			editor.putString( CommonConfig.PROPERTY_USERNAME, mUserNameTextField.getText().toString() );
		}
		
		if ( mPasswordTextField.getText().toString().trim().length() > 0 ) {
			editor.putString( CommonConfig.PROPERTY_PASSWORD, mPasswordTextField.getText().toString() );
		}
		
		editor.commit();
	}

	protected void showLocalConnectionView() {
		mLocalConnectionButton.setBackgroundColor( Color.GREEN );
		isLocalConnectionType = true;
		mRemoteConnectionButton.setBackgroundColor( Color.GRAY );
		mUserNameTextField.setHint( R.string.prompt_ip_address );
		mPasswordTextField.setVisibility( View.INVISIBLE );
		
		if ( mSettings.contains( CommonConfig.PROPERTY_IP ) ) {
			mUserNameTextField.setText( mSettings.getString( CommonConfig.PROPERTY_IP, "") );
		}
	}
	
	protected void showRemoteConnectionView() {
		mRemoteConnectionButton.setBackgroundColor( Color.GREEN );
		isLocalConnectionType = false;
		mLocalConnectionButton.setBackgroundColor( Color.GRAY );
		mUserNameTextField.setHint( R.string.prompt_email );
		mPasswordTextField.setVisibility( View.VISIBLE );
		
		if ( mSettings.contains( CommonConfig.PROPERTY_USERNAME ) ) {
			mUserNameTextField.setText( mSettings.getString( CommonConfig.PROPERTY_USERNAME, "") );
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mUserNameTextField.setError(null);
		mPasswordTextField.setError(null);

		// Store values at the time of the login attempt.
		mUsername = mUserNameTextField.getText().toString();
		mPassword = mPasswordTextField.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid username address.
		if (TextUtils.isEmpty(mUsername)) {
			mUserNameTextField.setError(getString(R.string.error_field_required));
			focusView = mUserNameTextField;
			cancel = true;
		} 
		
		if ( !isLocalConnectionType() ) {
			// Check for a valid password.
			if (TextUtils.isEmpty(mPassword)) {
				mPasswordTextField.setError(getString(R.string.error_field_required));
				focusView = mPasswordTextField;
				cancel = true;
			} else if (mPassword.length() < 4) {
				mPasswordTextField.setError(getString(R.string.error_invalid_password));
				focusView = mPasswordTextField;
				cancel = true;
			}
			
			 if ( !mUsername.contains("@")) {
				mUserNameTextField.setError(getString(R.string.error_invalid_email));
				focusView = mUserNameTextField;
				cancel = true;
			}
		} 
		
		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
		}
	}

	private boolean isLocalConnectionType() {
		return isLocalConnectionType;
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	public Socket getSocket() {
		return mSocket;
	}

	public void setSocket(Socket mSocket) {
		this.mSocket = mSocket;
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			boolean ret = false;
			if ( isLocalConnectionType() ) {	
				try {
					setSocket(new Socket( mUserNameTextField.getText().toString(), CommonConfig.PROPERTY_PORT));
					ret = true;
				} catch ( Exception e ) {
					Log.e("TCP", "S: Error", e);
					ret = false;
				}
			} else {
				try {
					// Simulate network access.
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					ret = false;
				}

				for (String credential : DUMMY_CREDENTIALS) {
					String[] pieces = credential.split(":");
					if (pieces[0].equals(mUsername)) {
						// Account exists, return true if the password matches.
						ret = pieces[1].equals(mPassword);
					}
				}
			}
			return ret;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			showProgress(false);

			if (success) {
				saveProperties();
				
				Intent intent = new Intent( LoginActivity.this, ControlActivity.class );

				CommonConfig.getInstance().setSocket( mSocket );
				SyncMessageHandler.instance.init( mSocket );
				startActivity( intent );
				finish();
			} else {
				mPasswordTextField.setError(getString(R.string.error_incorrect_password));
				mPasswordTextField.requestFocus();
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}
	}
}
